//
//  NewReportViewController.m
//  Project6
//
//  Created by ToanDK on 11/14/12.
//  Copyright (c) 2012 DungNP. All rights reserved.
//

#import "NewReportViewController.h"
#import "DamageReportViewController.h"
#import "EnterDataCell.h"
#import "StartButtonCell.h"
#import "EnterDataCell.h"


@implementation NewReportViewController
@synthesize  FARM_ID;
@synthesize  WTG_ID;
@synthesize  VIS_ID;
@synthesize DIS_LENGTH;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // set title
    self.title = self.FARM_ID;
    lblFARM_ID.text =[NSString stringWithFormat:@"FARM ID: %@",self.FARM_ID];
    lblWTG_ID.text = [NSString stringWithFormat:@"WTG ID: %@",self.WTG_ID];
    lblVIS_ID.text = self.VIS_ID;
    // set default value for 3 text filed
    currGenerated =  @"";
    currExTechName = @"";
    currPhotoId = @"";
    
    // init header sections
    headerSections = [[NSMutableArray alloc]  initWithObjects:
                      @"",
                      @"Access Method",
                      @"Side",
                      @"",
                      @"",
                      @"Photo ID",
                      nil];
    
    headerSectionIndexes = [[NSMutableArray alloc]initWithObjects:
                            @"0",
                            @"1",
                            @"2",
                            @"3",
                            @"4",
                            nil];
    
    
    // init content rows
    contentRows = [[NSMutableArray alloc] initWithCapacity:2];
    [contentRows addObject:@"Rope"];
    [contentRows addObject:@"Tension"];
    
    
    // init access methods
     AccessMethodItems = [[NSMutableArray alloc] initWithCapacity:7];
     [AccessMethodItems addObject:@"Rope"];
     [AccessMethodItems addObject:@"Crane"];
     [AccessMethodItems addObject:@"Cherry Picker"];
     [AccessMethodItems addObject:@"Truck Mounted Boom"];
     [AccessMethodItems addObject:@"Tower"];
     [AccessMethodItems addObject:@"Scope"];
    
    // init sides
    SideItems = [[NSMutableArray alloc] initWithCapacity:2];
    [SideItems addObject:@"Tension"];
    [SideItems addObject:@"Compression"];
    
    // set background for table
    [tblNewReportTable setBackgroundView:nil];
    UIView * bgView = [[UIView alloc] initWithFrame:tblNewReportTable.frame];
    bgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"greyBackground.png"]];
    [tblNewReportTable setBackgroundView:bgView];
    // set background for view
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"greyBackground"]];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundTapped)];
    [self.view addGestureRecognizer:tapGesture];
    tapGesture.cancelsTouchesInView = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)bladeSegmetation_ValueChange:(id)sender
{
    // retain selected index
    currBladeSelectedIndex = segmentedControl.selectedSegmentIndex;
}

-(IBAction)externalCamera_ChangeValue:(UISwitch *)sender
{
    if (sender.on)
    {
       // add new enter cell to table
        [headerSectionIndexes insertObject:@"5" atIndex:headerSectionIndexes.count -1];
    }
    else
    {
        [headerSectionIndexes removeObjectAtIndex:headerSectionIndexes.count -2];
    }
    // reload table
    [tblNewReportTable reloadData];
    
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Have 4 section.
    return headerSectionIndexes.count;
}

// display header section
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
    int index = [((NSString*)[headerSectionIndexes objectAtIndex:section]) intValue];
    return [headerSections objectAtIndex:index];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 3;
    }else
    {
        return 1;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    int cellType = [((NSString*)[headerSectionIndexes objectAtIndex:indexPath.section]) intValue];
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d-%d", indexPath.section, indexPath.row];
    UITableViewCell *cell;
    NSArray *nib;

    switch (cellType) {
        case 0:
            
            if(indexPath.row ==1 || indexPath.row ==2)
            {
                cell = (EnterDataCell *)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
                
                if (cell == nil)
                {
                    nib = [[NSBundle mainBundle] loadNibNamed:@"EnterDataCell"
                                                                 owner:self options:nil];
                    for (id oneObject in nib)
                        if ([oneObject isKindOfClass:[EnterDataCell class]])
                            cell = (EnterDataCell *)oneObject;
                }
                
                // Get the object to display and set the value in the cell
                if(indexPath.row ==1)
                {
                    ((EnterDataCell *)cell).tfEnterData.placeholder =@"Extra technicians name";
                    tfName = ((EnterDataCell *)cell).tfEnterData;
                    tfName.text = currExTechName;
                    
                }
                else
                {
                    ((EnterDataCell *)cell).tfEnterData.placeholder = @"Generated(mwh)";
                    tfGenerated = ((EnterDataCell *)cell).tfEnterData;
                    tfGenerated.text = currGenerated;
                    if(UIUserInterfaceIdiomPhone)
                        [tfGenerated setKeyboardType:UIKeyboardTypeDecimalPad];
                    else
                        [tfGenerated setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
                }
                
                [tfName setDelegate:self];
                [tfGenerated setDelegate:self];
                
            }
            else if(indexPath.row==0)
            {
                cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                
                if(cell ==nil)
                {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                }
                
                // None selected
                cell.selectionStyle =UITableViewCellSelectionStyleNone;
                
                // Get the object to display and set the value in the cell.
                NSString *rowContent = @"Blade";
                cell.textLabel.text = rowContent;
                // add segmentation controll
                NSArray *itemArray = [NSArray arrayWithObjects: @"A", @"B", @"C", nil];
                segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
                segmentedControl.frame = CGRectMake(200, 10, 100, 30);
                segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
                segmentedControl.selectedSegmentIndex = currBladeSelectedIndex;
    
                // Change font attributes
                UIFont *font = [UIFont boldSystemFontOfSize:13.0f];
                NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                             forKey:UITextAttributeFont];
                [segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];
                // add action to target
                [segmentedControl addTarget:self action:@selector(bladeSegmetation_ValueChange:) forControlEvents:UIControlEventValueChanged];
                
                [cell addSubview:segmentedControl];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            break;
            
        case 1:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            if(cell ==nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.text = [contentRows objectAtIndex:0];
            cell.selectionStyle =UITableViewCellSelectionStyleGray;
            
            cell.accessoryView = [[ UIImageView alloc ]
                                    initWithImage:[UIImage imageNamed:@"AccessoryDisclosure.png" ]];
            cell.accessoryView.bounds = CGRectMake(0, 0, 25, 25);
            
           break;
        case 2:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            if(cell ==nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.text = [contentRows objectAtIndex:1];
            cell.selectionStyle =UITableViewCellSelectionStyleGray;
            cell.accessoryView = [[ UIImageView alloc ]
                                  initWithImage:[UIImage imageNamed:@"AccessoryDisclosure.png" ]];
            cell.accessoryView.bounds = CGRectMake(0, 0, 25, 25);
            
            break;
        case 3:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            if(cell ==nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            cell.textLabel.text =@"External Camera";
            if (!externalCamera)
            {
                externalCamera = [[UISwitch alloc] initWithFrame:CGRectMake(220, 10, 120, 30)];
           
                [externalCamera addTarget:self action:@selector(externalCamera_ChangeValue:) forControlEvents:UIControlEventValueChanged];
            }
            [cell addSubview:externalCamera];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            break;
        case 4:
            cell = (ButtonCell *)[tableView
                                              dequeueReusableCellWithIdentifier: CellIdentifier];
            if (cell == nil) {
                nib = [[NSBundle mainBundle] loadNibNamed:@"StartButtonCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[ButtonCell class]])
                        cell = (ButtonCell *)oneObject;
                [cell.contentView setBackgroundColor:[UIColor clearColor]];
                [cell setBackgroundView:nil];
                [cell setBackgroundColor:[UIColor clearColor]];
            }
            
            [((ButtonCell *)cell).startButton addTarget:self action:@selector(btnStart_Click:) forControlEvents:UIControlEventTouchUpInside];
            
            [cell.contentView setBackgroundColor:[UIColor clearColor]];
            [cell setBackgroundView:nil];
            [cell setBackgroundColor:[UIColor clearColor]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            break;
        case 5:
            cell = (EnterDataCell *)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
            
            if (cell == nil) {
                nib = [[NSBundle mainBundle] loadNibNamed:@"EnterDataCell"
                                                    owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[EnterDataCell class]])
                        cell = (EnterDataCell *)oneObject;
            }
            
            tfPhotoId = ((EnterDataCell*)cell).tfEnterData;
            tfPhotoId.text = currPhotoId;
            tfPhotoId.delegate = self;
            if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
                tfPhotoId.keyboardType = UIKeyboardTypeDecimalPad;
            else
                tfPhotoId.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            break;
        default:
            break;
    }
	   
    return cell;
}



// selected specified row event handle
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tblNewReportTable selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    
    if(indexPath.section==1) // access method
    {
        mode = 0;
        [self showPickerWithMode];
    }
    else if(indexPath.section==2) // side method
    {
        mode = 1;
        [self showPickerWithMode];
    }
    
}


-(void)showPickerWithMode
{
    // Scroll table view toi do
    if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
    {
        [UIView animateWithDuration:0.3f animations:^{
            [view1 setFrame:CGRectMake(0, 160, 320, 260)];
        }];
    }
    else // ipad
    {
        [UIView animateWithDuration:0.3f animations:^{
            [view1 setFrame:CGRectMake(0, 700, 768, 260)];
        }];
        
        
    }
    
    if (mode==0)
    {
        picker.hidden = NO;
        [picker reloadAllComponents];
         picker2.hidden = YES;
    }
    else
    {
        picker2.hidden = NO;
        [picker2 reloadAllComponents];
        picker.hidden =YES;
    }
    
    
}

-(void)hidePicker
{
    CGRect viewFrame = CGRectMake(0, 420, 320, 260);
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        viewFrame = CGRectMake(0, 1000, 768, 260);
    [UIView animateWithDuration:0.3f animations:^{
        [view1 setFrame:viewFrame];
    }];
    
    [tblNewReportTable reloadData];
}



#pragma mark -UIPicker Datasource
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (mode) {
        case 0:
            //Access method
        {
            return AccessMethodItems.count;
        }
            break;
        case 1:
            //TensionSide
        {
            return SideItems.count;
        }
        default:
            break;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString* title;
    switch (mode) {
        case 0:
            //Access methods
        {
            title = [AccessMethodItems objectAtIndex:row];
        }
            break;
        case 1:
            //Sides
        {
            title = [SideItems objectAtIndex:row];
        }
            break;
        default:
            break;
    }
    return title;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (mode) {
        case 0: // Access methods
            [contentRows replaceObjectAtIndex:0 withObject:[AccessMethodItems objectAtIndex:row]];
            break;
        case 1: // Sides
            [contentRows replaceObjectAtIndex:1 withObject:[SideItems objectAtIndex:row]];
            break;
        default:
            break;
    }
    
    [tblNewReportTable reloadData];
}


#pragma mark - textfield keyboard
-(void)backgroundTapped
{
    [self.view endEditing:YES];
    NSLog(@"backgroundTapped");

}


#pragma  TextFile and ScrollView Delegate implement
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"textFieldShouldReturn");
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
//    tblNewReportTable.frame = CGRectMake(tblNewReportTable.frame.origin.x,tblNewReportTable.frame.origin.y, tblNewReportTable.frame.size.width, tblNewReportTable.frame.size.height/2);
    
    // Scroll table view toi do
    CGPoint point = [textField.superview convertPoint:textField.frame.origin toView:tblNewReportTable];
    NSIndexPath *indexPath = [tblNewReportTable indexPathForRowAtPoint:point];
    NSLog(@"row:%d",indexPath.row);
    NSLog(@"section:%d",indexPath.section);
    [tblNewReportTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewRowAnimationTop animated:YES];
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    // retain text field
    if ([textField isEqual:tfName])
    {
        currExTechName = tfName.text;
    }
    else if([textField isEqual:tfGenerated])
    {
        currGenerated = tfGenerated.text;
    }
    else
    {
        currPhotoId = tfPhotoId.text;
    }
    
//    tblNewReportTable.frame = CGRectMake(tblNewReportTable.frame.origin.x,tblNewReportTable.frame.origin.y, tblNewReportTable.frame.size.width, tblNewReportTable.frame.size.height*2);
    
    [textField resignFirstResponder];
}


// handle start button click
-(IBAction)btnStart_Click:(id)sender
{
    NSLog(@"btnStart_Click");
    // go to Damage New report
    DamageReportViewController *damageNewReport = [[DamageReportViewController alloc] initWithNibName:@"DamageReportViewController" bundle:nil];
    NSMutableDictionary * reportInfoDic = [[NSMutableDictionary alloc] initWithCapacity:9];
   
    // API, UDID, INSPECTDATE, WFID, WTGID, BLADE, WTGVISID, generated , access, side
    NSString * API = @"xd7er2";
    NSString *uniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];
    // get blade
    NSString * blade=@"";
    switch (segmentedControl.selectedSegmentIndex) {
        case 0:
            blade =@"A";
            break;
        case 1:
            blade =@"B";
            break;
        default:
            blade =@"C";
            break;
    }
    
    [reportInfoDic setObject:API forKey:@"api"];
    [reportInfoDic setObject:uniqueIdentifier forKey:@"udid"];
    [reportInfoDic setObject:self.FARM_ID forKey:@"wfid"];
    [reportInfoDic setObject:self.WTG_ID forKey:@"wtgid"];
    [reportInfoDic setObject:blade forKey:@"blade"];
    if (self.VIS_ID==nil) {
        self.VIS_ID =@"test";
    }
    [reportInfoDic setObject:self.VIS_ID forKey:@"wtgvisid"];
    [reportInfoDic setObject:tfGenerated.text forKey:@"generated"];
    [reportInfoDic setObject:[NSString stringWithFormat:@"%@", [contentRows objectAtIndex:0]] forKey:@"access"];
    [reportInfoDic setObject:[NSString stringWithFormat:@"%@", [contentRows objectAtIndex:1] ] forKey:@"side"];
    [reportInfoDic setObject:tfName.text forKey:@"extratech"];
    if (tfPhotoId ==nil) {
         [reportInfoDic setObject:@"" forKey:@"extcam"];
    }else
        [reportInfoDic setObject:tfPhotoId.text forKey:@"extcam"];
   
    
    // get newreport id from plist file
    NSString * newreportid= [self getNewReportIdFromPlistDB:@"newreport.plist"];
    [reportInfoDic setObject:newreportid forKey:@"newreportid"];
    
    // test
    NSLog(@"Report Info:%@",[reportInfoDic description]);
    
    // assign to property of damage report
    damageNewReport.ReportDictInfo = reportInfoDic;
    damageNewReport.distanceMaxLength = self.DIS_LENGTH;
    [self.navigationController pushViewController:damageNewReport animated:YES];
    
}


-(NSString *) getNewReportIdFromPlistDB:(NSString *) filePath
{
    NSString * rv =@"0";
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *newReportPath = [documentsDirectory stringByAppendingPathComponent:filePath];
    
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	BOOL success = [fileManager fileExistsAtPath:newReportPath];
    NSLog(@"newReportPath:%@",newReportPath);
    NSMutableArray * suspendNewReports = [[NSMutableArray alloc] initWithCapacity:0];
    if (success) {
        suspendNewReports = [NSMutableArray arrayWithContentsOfFile:newReportPath];
        rv = [NSString stringWithFormat:@"%d",suspendNewReports.count];
    }
   
    
    return rv;
}

-(IBAction)pickerDone_Click:(id)sender
{
    // hide pickerview
    [self hidePicker];
}

@end
